/*
 * Created on Feb 15, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell.ui;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.NodeIterator;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;

import edu.mit.simile.longwell.Profile;
import edu.mit.simile.longwell.query.Query;
import edu.mit.simile.longwell.query.bucket.DistinctValueBucketer;
import edu.mit.simile.longwell.query.project.SchemaBasedProjector;
import edu.mit.simile.longwell.schema.ISchemaModel;
import edu.mit.simile.longwell.schema.IStructuredSchema;

/**
 * @author dfhuynh
 */
public class SchemaBasedFacade extends Facade {
	final static protected String s_flair_schema = Flair.s_namespace + "schema";
	
	final protected Set	m_sSchemas;

	/**
	 * @param uri
	 * @param shortLabel
	 * @param contentDescription
	 * @param initialQuery
	 */
	public SchemaBasedFacade(
		String uri,
		String shortLabel,
		String contentDescription,
		String initialQuery,
		Set		sSchemas) {

		super(uri, shortLabel, contentDescription, initialQuery);

		m_sSchemas = sSchemas;
	}
	
	/* (non-Javadoc)
	 * @see edu.mit.simile.longwell.ui.Facade#getCount()
	 */
	public int getCount() {
		updateCount();
		return super.getCount();
	}

	protected void updateCount() {
		m_count = 0;

		Iterator i = m_sSchemas.iterator();
		while (i.hasNext()) {
			IStructuredSchema sSchema = (IStructuredSchema) i.next();

			m_count += sSchema.countObjects();
		}
	}
	
	static public SchemaBasedFacade constructFacade(
			Resource r, 
			String shortLabel, 
			String contentDescription, 
			Model model, 
			Profile profile) {
		
		ISchemaModel schemaModel = profile.getSchemaModel();
		
		Set sSchemas = new HashSet();
		String schemas = "";

		NodeIterator ni = model.listObjectsOfProperty(
			r, model.createProperty(s_flair_schema));
		while (ni.hasNext()) {
			RDFNode node = ni.nextNode();
			String uri = null;
			if (node instanceof Literal) {
				uri = ((Literal) node).getString();
			} else {
				uri = ((Resource) node).getURI();
			}

			sSchemas.add(schemaModel.getStructuredSchema(uri));

			if (schemas.length() == 0) {
				schemas = "r" + uri;
			} else {
				schemas += ",r" + uri;
			}
		}

		String initialQuery = 
			Query.s_restrictionPrefix + "=" +
			SchemaBasedProjector.class.getName() +
				Query.s_separator +
				Query.s_separator +
			DistinctValueBucketer.class.getName() +
				Query.s_separator +
				schemas;
		
		return new SchemaBasedFacade(
			r.getURI(),
			shortLabel,
			contentDescription,
			initialQuery,
			sSchemas
		);
	}
}
